package com.demo.javase.day79;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * @Author bug菌
 * @Date 2023-12-27 18:03
 */
public class FileCompression {
    public static void compressFile(File sourceFile, File compressedFile) throws IOException {
        FileInputStream fis = new FileInputStream(sourceFile);
        FileOutputStream fos = new FileOutputStream(compressedFile);
        ZipOutputStream zos = new ZipOutputStream(fos);
        ZipEntry ze = new ZipEntry(sourceFile.getName());
        zos.putNextEntry(ze);
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.read(buffer)) > 0) {
            zos.write(buffer, 0, len);
        }
        zos.closeEntry();
        zos.close();
        fos.close();
        fis.close();
    }

    public static void decompressFile(File compressedFile, File destinationFile) throws IOException {
        FileInputStream fis = new FileInputStream(compressedFile);
        ZipInputStream zis = new ZipInputStream(fis);
        FileOutputStream fos = new FileOutputStream(destinationFile);
        ZipEntry ze = zis.getNextEntry();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = zis.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
        }
        zis.closeEntry();
        zis.close();
        fos.close();
        fis.close();
    }
}